App({
  globalData: {
    env: "cloud1-2g8begsidb0e834d",
    userInfo: null,
    userProfileComplete: false
  },

  _loadingCounter: 0,

  onLaunch: function () {
    if (!wx.cloud) {
      console.error("请使用 2.2.3 或以上基础库以使用云能力");
      return;
    }

    wx.cloud.init({
      env: this.globalData.env,
      traceUser: true
    });

    // 调用 logIn 获取用户信息
    this.callCloudFunction({
      name: "logIn",
      data: {},
      loadingTitle: "登录中...",
      success: res => {
        const result = res.result;
        if (!result) {
          wx.showToast({ title: "登录失败", icon: "error" });
          return;
        }

        // 保存全局 userInfo
        this.globalData.userInfo = {
          openID: result.openID,
          nickname: result.nickname,
          avatar: result.avatar,
          name: result.name,
          gender: result.gender,
          studentID: result.studentID,
          studentType: result.studentType,
          enrollmentYear: result.enrollmentYear,
          college: result.college,
          major: result.major,
          phoneNumber: result.phoneNumber,
          isUnregistered: result.isUnregistered
        };
        this.updateUserProfileState(this.globalData.userInfo);
      },
      fail: err => {
        console.error("logIn 调用失败:", err);
        wx.showToast({ title: "登录失败", icon: "error" });
      }
    });
  },

  showGlobalLoading(title = "加载中...") {
    const normalized = typeof title === "string" ? title.trim() : "";
    const displayTitle = normalized || "加载中...";
    if (typeof this._loadingCounter !== "number") {
      this._loadingCounter = 0;
    }
    this._loadingCounter += 1;
    if (this._loadingCounter === 1) {
      wx.showLoading({ title: displayTitle, mask: true });
    }
  },

  hideGlobalLoading(force = false) {
    if (typeof this._loadingCounter !== "number") {
      this._loadingCounter = 0;
    }
    if (force) {
      this._loadingCounter = 0;
      wx.hideLoading();
      return;
    }
    if (this._loadingCounter > 0) {
      this._loadingCounter -= 1;
    }
    if (this._loadingCounter <= 0) {
      this._loadingCounter = 0;
      wx.hideLoading();
    }
  },

  updateUserProfileState(user) {
    if (user) {
      this.globalData.userProfileComplete = this.isUserProfileComplete(user);
    } else {
      this.globalData.userProfileComplete = false;
    }
  },

  isUserProfileComplete(user) {
    const target = user || this.globalData.userInfo;
    if (!target || target.isUnregistered) {
      return false;
    }
    const hasGender = target.gender === 1 || target.gender === 2;
    const hasStudentType = [1, 2, 3].includes(target.studentType);
    const enrollmentYear = target.enrollmentYear;
    const hasEnrollmentYear =
      enrollmentYear !== null &&
      enrollmentYear !== undefined &&
      String(enrollmentYear).trim() !== "";
    const requiredFields = [
      "nickname",
      "name",
      "studentID",
      "college",
      "major",
      "phoneNumber"
    ];
    const hasRequiredFields = requiredFields.every(field => {
      const value = target[field];
      if (value === null || value === undefined) return false;
      return String(value).trim() !== "";
    });
    return hasGender && hasStudentType && hasEnrollmentYear && hasRequiredFields;
  },

  ensureUserProfileForAction(message) {
    const user = this.globalData.userInfo;
    if (!user) {
      wx.showToast({ title: "正在获取用户信息，请稍后再试", icon: "none" });
      return false;
    }
    this.updateUserProfileState(user);
    if (this.globalData.userProfileComplete) {
      return true;
    }
    const content =
      typeof message === "string" && message.trim()
        ? message.trim()
        : "操作前请先完善个人信息";
    wx.showModal({
      title: "完善信息",
      content,
      confirmText: "去完善",
      cancelText: "暂不",
      success: res => {
        if (res && res.confirm) {
          const pages = typeof getCurrentPages === "function" ? getCurrentPages() : [];
          const currentPage = Array.isArray(pages) && pages.length > 0 ? pages[pages.length - 1] : null;
          if (currentPage && currentPage.route === "pages/userInfo/userInfo") {
            return;
          }
          wx.navigateTo({ url: "/pages/userInfo/userInfo" });
        }
      }
    });
    return false;
  },

  callCloudFunction(options = {}) {
    const { loadingTitle, showLoading = true, ...callOptions } = options;
    if (!callOptions.name) {
      return Promise.reject(new Error("缺少云函数名称"));
    }
    const title =
      typeof loadingTitle === "string" && loadingTitle.trim()
        ? loadingTitle.trim()
        : "加载中...";
    const shouldShow = showLoading !== false;

    if (shouldShow) {
      this.showGlobalLoading(title);
    }

    const { success, fail, complete } = callOptions;

    callOptions.success = (...args) => {
      if (typeof success === "function") {
        try {
          success(...args);
        } catch (error) {
          console.error("callCloudFunction success 回调异常", error);
        }
      }
    };

    callOptions.fail = (...args) => {
      if (typeof fail === "function") {
        try {
          fail(...args);
        } catch (error) {
          console.error("callCloudFunction fail 回调异常", error);
        }
      }
    };

    callOptions.complete = (...args) => {
      if (shouldShow) {
        this.hideGlobalLoading();
      }
      if (typeof complete === "function") {
        try {
          complete(...args);
        } catch (error) {
          console.error("callCloudFunction complete 回调异常", error);
        }
      }
    };

    return wx.cloud.callFunction(callOptions);
  }
});
